﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using MSP.Business.UserManagement;
using MSP.Data.Domain;
using MSP.UI.Helpers;
using System.IO;
using DevExpress.XtraEditors.DXErrorProvider;
using MSP.Business.ProductManagement;

namespace MSP.UI.Forms
{
    public partial class xfrmProducts : DevExpress.XtraEditors.XtraForm
    {
        ProductManager productManager = new ProductManager();
        ProductCategoryManager productCategoryManager = new ProductCategoryManager();
        CurrencyManager manager;
        int LastFocusedRowHandle;

        public xfrmProducts()
        {
            InitializeComponent();
        }

        private void xfrmProducts_Load(object sender, EventArgs e)
        {
            LastFocusedRowHandle = -1;
            FormLoad();
        }

        void FormLoad()
        {
            InKdvCheckEdit.Checked = true;
            dsProduct1.Product.Clear();
            List<Product> products = productManager.GetAllProduct().ToList();
            if (products.Count <= 0)
            {
                btnSave.Enabled = false;
                btnDelete.Enabled = false;
            }
            DataTable dtProducts = EnumerableExtension.ToDataTable(products);
            dtProducts.TableName = "Product";
            foreach (DataRow item in dtProducts.Rows)
            {
                dsProduct1.Product.LoadDataRow(item.ItemArray, LoadOption.OverwriteChanges);
            }
            dsProduct1.Product.PrimaryKey = new DataColumn[] { dsProduct1.Product.Columns["Id"] };

            manager = dataLayoutControl1.BindingContext[dataLayoutControl1.DataSource, dataLayoutControl1.DataMember] as CurrencyManager;

            ProductCategoryLookUpEdit.Properties.DataSource = productCategoryManager.GetAllProductCategory();
            ProductCategoryLookUpEdit.Properties.DisplayMember = "Name";
            ProductCategoryLookUpEdit.Properties.ValueMember = "Id";
            ProductCategoryLookUpEdit.Properties.Columns.Clear();
            ProductCategoryLookUpEdit.Properties.Columns.Add(new DevExpress.XtraEditors.Controls.LookUpColumnInfo("Name", "Kategori Adı"));

            UnitIdLookUpEdit.Properties.DataSource = productManager.GetAllUnit();
            UnitIdLookUpEdit.Properties.DisplayMember = "Name";
            UnitIdLookUpEdit.Properties.ValueMember = "Value";
            UnitIdLookUpEdit.Properties.Columns.Clear();
            UnitIdLookUpEdit.Properties.Columns.Add(new DevExpress.XtraEditors.Controls.LookUpColumnInfo("Name", "Birim"));

            InitValidationRules();
        }

        private void InitValidationRules()
        {
            // <notEmptyTextEdit> 
            ConditionValidationRule notEmptyValidationRule = new ConditionValidationRule();
            notEmptyValidationRule.ConditionOperator = ConditionOperator.IsNotBlank;
            notEmptyValidationRule.ErrorText = "Lütfen değer giriniz";
            // </notEmptyTextEdit>

            // <notSelectValidationRule>
            ConditionValidationRule notSelectValidationRule = new ConditionValidationRule();
            notSelectValidationRule.ConditionOperator = ConditionOperator.NotEquals;
            notSelectValidationRule.Value1 = null;
            notSelectValidationRule.ErrorText = "Lütfen seçiniz";
            // </notSelectValidationRule>

            //notEmptyValidationRule
            dxValidationProvider1.SetValidationRule(BarcodeTextEdit, notEmptyValidationRule);
            dxValidationProvider1.SetValidationRule(NameTextEdit, notEmptyValidationRule);


            //notSelectValidationRule
            dxValidationProvider1.SetValidationRule(ProductCategoryLookUpEdit, notSelectValidationRule);
            dxValidationProvider1.SetValidationRule(UnitIdLookUpEdit, notSelectValidationRule);


            //dxValidationProvider1.ValidationMode = ValidationMode.Auto;
        }

        private void grdSearch_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            RowChanged(e.FocusedRowHandle);
        }

        void RowChanged(int FocusedRowHandle)
        {
            manager.CancelCurrentEdit();
            btnNew.Enabled = true;
            btnDelete.Enabled = true;
            btnSave.Enabled = true;

            if (grdSearch.DataRowCount <= 0)
            {
                btnSave.Enabled = false;
                btnDelete.Enabled = false;
            }

            if (FocusedRowHandle >= 0)
            {
                DataRow dr = grdSearch.GetDataRow(FocusedRowHandle);
                int id = Convert.ToInt32(dr["Id"]);
                if (id >= 0)
                {

                    if (string.IsNullOrEmpty(dsProduct1.Product.DefaultView.Sort))
                    {
                        dsProduct1.Product.DefaultView.Sort = "Id";
                    }

                    DataRowView[] drwList = dsProduct1.Product.DefaultView.FindRows(id);

                    if (drwList != null && drwList.Length > 0)
                    {
                        int i = 0;
                        foreach (DataRowView drw in manager.List)
                        {
                            if (drw.Row == drwList[0].Row)
                            {
                                manager.Position = i;
                                break;
                            }
                            i++;
                        }
                    }
                }

                dxValidationProvider1.Validate();
            }
          
        }

        private void btnNew_Click(object sender, EventArgs e)
        {
            manager.AddNew();
            grdMaster.Enabled = false;
            btnNew.Enabled = false;
            btnDelete.Enabled = true;
            btnSave.Enabled = true;
            InKdvCheckEdit.Checked = true;
            IdTextEdit.Text = "0";
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            DialogResult ds = MessageBox.Show("Silmek istediğize emin misiniz?", "?", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);

            if (ds != DialogResult.Yes || manager.Position == -1)
            {
                return;
            }

            DataRowView drv = (DataRowView)manager.Current;
            if (drv.Row.RowState != DataRowState.Detached)
            {
                drv.Row.SetModified();
                DataTable dtDeletedProducts = dsProduct1.Product.GetChanges(DataRowState.Modified);
                List<Product> retList = EnumerableExtension.ToList<Product>(dtDeletedProducts);
                if (retList.Count == 1)
                {
                    foreach (Product item in retList)
                    {
                        bool result = productManager.DeleteProduct(item);
                    }
                }

                LastFocusedRowHandle = grdSearch.FocusedRowHandle - 1;
                FormLoad();
                grdSearch.FocusedRowHandle = LastFocusedRowHandle;
            }
            else
            {
                manager.CancelCurrentEdit();
            }
            RowChanged(grdSearch.FocusedRowHandle);
            grdMaster.Enabled = true;
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (!dxValidationProvider1.Validate() || dxErrorProvider1.HasErrors)
            {
                return;
            }
            manager.EndCurrentEdit();

            DataRowView drv = (DataRowView)manager.Current;

            if (drv.Row.RowState == DataRowState.Added)
            {
                DataTable dtAddedProducts = drv.Row.Table.GetChanges(DataRowState.Added);
                List<Product> retList = EnumerableExtension.ToList<Product>(dtAddedProducts);

                foreach (Product item in retList)
                {
                    int id = productManager.SaveProduct(item);

                }
                LastFocusedRowHandle = dsProduct1.Product.Count - 1;
                FormLoad();
                grdSearch.FocusedRowHandle = LastFocusedRowHandle;
            }
            else if (drv.Row.RowState == DataRowState.Modified)
            {
                DataTable dtEditedProducts = drv.Row.Table.GetChanges(DataRowState.Modified);
                List<Product> retList = EnumerableExtension.ToList<Product>(dtEditedProducts);

                foreach (Product item in retList)
                {
                    bool result = productManager.UpdateProduct(item);
                }
                LastFocusedRowHandle = grdSearch.FocusedRowHandle;
                FormLoad();
                grdSearch.FocusedRowHandle = LastFocusedRowHandle;
            }
            else if (drv.Row.RowState == DataRowState.Deleted)
            {

            }

            grdMaster.Enabled = true;
            btnNew.Enabled = true;
            btnDelete.Enabled = true;
            btnSave.Enabled = true;
        }

        private void BarcodeTextEdit_Validating(object sender, CancelEventArgs e)
        {
            Product pd = productManager.GetProductByBarcode(BarcodeTextEdit.Text);

            if (pd != null && pd.Id != Convert.ToInt32(IdTextEdit.Text))
            {
                e.Cancel = true;
                dxErrorProvider1.SetError(BarcodeTextEdit, "Bu barkod başka üründe kullanılmış", ErrorType.Warning);
            }
            else
            {
                dxErrorProvider1.SetError(BarcodeTextEdit, "");
            }

        }
    }
}